package com.smartrobot.smartrobot.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.smartrobot.smartrobot.R;
import com.smartrobot.smartrobot.adapter.StoreActiveAdapter;
import com.smartrobot.smartrobot.util.FileUtil;
import com.smartrobot.smartrobot.util.HttpUtil;
import com.smartrobot.smartrobot.util.NetWorkUtil;
import com.smartrobot.smartrobot.util.StoreActive;
import com.smartrobot.smartrobot.util.User;
import com.smartrobot.smartrobot.view.ExlistenListView;
import com.smartrobot.smartrobot.view.ToastCustom;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/1/20.
 */
public class StoreActiveActivity extends Activity implements View.OnClickListener {

    private ImageView back;
    private TextView progressTxt;
    private ExlistenListView listView;
    private StoreActiveAdapter adapter;
    private List<StoreActive> storeActiveList;
    private StoreActiveHandler handler;
    private Map<String,String> map;
    private String fileName = FileUtil.newsCachePath + User.getInstance().getId() + User.getInstance().getPhone() +FileUtil.storeActiveEndName;
    private Thread initThread;

    private boolean isGetting = false;
    private boolean isFirst = true;

    private final int HANDLER_READ_FILE = 1221;
    private final int HANDLER_READ_SERVER = 1222;
    private final int HANDLER_UPDATE_NEW = 1223;
    private final int HANDLER_UPDATE_OLD = 1224;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState != null){
            throw new NullPointerException();
        }
        this.setContentView(R.layout.page_store_active);

        init();

    }

    void init(){
        initView();
        HttpUtil.init(getApplicationContext());
        initThread = new Thread(new StoreActiveInitThread());
        map = new HashMap<String, String>();
        if(!NetWorkUtil.isHasNetWork(getApplicationContext())) {//没有网络读取本地文件，有网络直接读取网络文件
            initThread.start();
            isFirst = false;
        }
        else {
            Message msg = new Message();
            msg.what = HANDLER_READ_SERVER;
            handler.sendMessage(msg);

        }

    }

    void initView(){

        handler = new StoreActiveHandler();

        listView = (ExlistenListView)findViewById(R.id.store_active_listview);
        progressTxt = (TextView)findViewById(R.id.store_active_progresstxt);
        back = (ImageView)findViewById(R.id.store_active_back);

        storeActiveList = new ArrayList<StoreActive>();

        adapter = new StoreActiveAdapter(getApplicationContext());


        listView.setAdapter(adapter);
        listView.setOnItemClickListener(adapter);
        back.setOnClickListener(this);


        listView.setOnUdateNewListender(new ExlistenListView.UdateNewListener() {
            @Override
            public void updateNew() {

                Message msg = new Message();
                msg.what = HANDLER_UPDATE_NEW;
                handler.sendMessage(msg);

            }
        });
        listView.setOnUdateOldListener(new ExlistenListView.UdateOldListener() {
            @Override
            public void updateOld() {

                Message msg = new Message();
                msg.what = HANDLER_UPDATE_OLD;
                handler.sendMessage(msg);

            }
        });




    }

    @Override
    public void onClick(View view) {

        switch (view.getId()){

            case R.id.store_active_back://结束activity

                StoreActiveActivity.this.finish();

                break;

        }

    }

    class StoreActiveInitThread implements Runnable{

        @Override
        public void run() {

            Looper.prepare();
            storeActiveList = FileUtil.readStoreActiveFromFile(fileName);
            Message msg = new Message();
            msg.what = HANDLER_READ_FILE;
            handler.sendMessage(msg);

        }
    }


    class StoreActiveHandler extends Handler {

        @Override
        public void dispatchMessage(Message msg) {



            switch (msg.what){

                case HANDLER_READ_FILE:

                    Log.d("==============>","读取本地缓存");
                    adapter.notiNewDataChange(storeActiveList);
                    isGetting = false;
                    if(User.getInstance().getRole().equals("客户") ){
                       if(User.getInstance().getBarberId().equals("未填写")){

                           progressTxt.setText("您还没有加入理发师，无法查看店内活动!");
                           progressTxt.setVisibility(View.VISIBLE);
                           listView.setVisibility(View.GONE);

                           //加载完成显示listview
                       }else{
                           progressTxt.setVisibility(View.GONE);
                           listView.setVisibility(View.VISIBLE);
                       }

                    }else{
                        progressTxt.setVisibility(View.GONE);
                        listView.setVisibility(View.VISIBLE);
                    }

                    if(storeActiveList.size() == 0){
                        ToastCustom.showToast(getApplicationContext(),"暂时没有店内活动!");
                    }


                    break;

                case HANDLER_READ_SERVER:

                    if(!isGetting) {
                        isGetting = true;
                        map = new HashMap<String, String>();
                        map.put("num", "10");
                        map.put("way", "up");
                        map.put("lastTime", adapter.getNewUpdateTime());
                        storeActiveList.clear();
                        HttpUtil.apiGetStoreActive(map, storeActiveList, handler);
                    }
                    break;

                case HANDLER_UPDATE_NEW:

                    if(!isGetting) {
                        isGetting = true;
                        map = new HashMap<String, String>();
                        map.put("num", "10");
                        map.put("way", "up");
                        map.put("lastTime", adapter.getNewUpdateTime());
                        storeActiveList.clear();
                        HttpUtil.apiGetStoreActive(map, storeActiveList, handler);
                    }

                    progressTxt.setVisibility(View.GONE);
                    listView.setVisibility(View.VISIBLE);

                    break;


                case HANDLER_UPDATE_OLD:

                    Log.e("更新旧的===>", "------------------");
                    if(!isGetting) {
                        isGetting = true;
                        map = new HashMap<String, String>();
                        map.put("num", "10");
                        map.put("way", "low");
                        map.put("lastTime", adapter.getOldUpdateTime());
                        storeActiveList.clear();
                        HttpUtil.apiGetStoreActive(map, storeActiveList, handler);
                    }

                    progressTxt.setVisibility(View.GONE);
                    listView.setVisibility(View.VISIBLE);

                    break;

                case HttpUtil.GET_STORE_ACTIVE_SUCCESS:

                    isFirst = false;//不是第一次
                    if(msg.obj != null){
                        if(msg.obj.equals("up"))
                           adapter.notiNewDataChange(storeActiveList);
                        else
                            adapter.notiOldDataChange(storeActiveList);
                    }


                    isGetting = false;
                    listView.changeState();
                    listView.hiddenFooter();
                    progressTxt.setVisibility(View.GONE);
                    listView.setVisibility(View.VISIBLE);

                    break;

                case HttpUtil.GET_STORE_ACTIVE_FAILD:
                    isFirst = false;//不是第一次
                    isGetting = false;
                    progressTxt.setVisibility(View.GONE);

                    if(msg.obj != null){

                        if(msg.obj.equals("105")){
                            if(msg.arg1 == 0){
//                                ToastCustom.showToast(getApplicationContext(),"没有了╮(╯▽╰)╭");
                                listView.hiddenFooter();
                                listView.changeState();
                            }

                        }

                        if(msg.obj.equals("100")){

                            HttpUtil.reLogin(getApplication(),handler);
                            isGetting = true;
                        }

                        if(msg.obj.equals("104")){
                            listView.setVisibility(View.GONE);
                            progressTxt.setVisibility(View.VISIBLE);
                            progressTxt.setText("您还没有加入理发师，无法查看店内活动!");
                        }

                    }else{
                        ToastCustom.showToast(getApplicationContext(),"网络异常，请稍后再试！");
                        listView.hiddenFooter();
                        listView.changeState();
                    }




                    break;

                case HttpUtil.GET_STORE_ACTIVE_FAILD_NETWORK://由于网络问题导致出现错误

                    if(isFirst) //若是第一次有问题就读取文件
                    {
                        isFirst = false;
                        if( User.getInstance().getRole().equals("客户"))
                        {
                            if(!User.getInstance().getBarberId().equals("未填写"))
                                 initThread.start();
                            else{
                                progressTxt.setVisibility(View.VISIBLE);
                                progressTxt.setText("您还没有加入理发师，无法查看店内活动!");

                            }
                        }
                        else
                        {
                            initThread.start();
                            progressTxt.setVisibility(View.VISIBLE);
                            listView.setVisibility(View.GONE);
                        }
                    }else
                        ToastCustom.showToast(getApplicationContext(),"网络异常，请稍后再试！");

                    isGetting = false;
                    listView.changeState();
                    listView.hiddenFooter();

                    break;

                case HttpUtil.LOGIN_SUCCESS:

                    //重新一次获取
                    HttpUtil.apiGetStoreActive(map,storeActiveList,handler);
                    progressTxt.setVisibility(View.GONE);

                    break;

                case HttpUtil.LOGIN_FAILD:

                    ToastCustom.showToast(getApplicationContext(),"网络异常，请稍后再试！");
                    listView.hiddenFooter();
                    listView.changeState();
                    isGetting = false;
                    progressTxt.setVisibility(View.GONE);
                    listView.setVisibility(View.VISIBLE);

                    break;


            }




        }
    }

    @Override
    protected void onRestart() {
        //重新初始化
        if(storeActiveList == null)
            storeActiveList = new ArrayList<StoreActive>();
        if(handler == null)
            handler = new StoreActiveHandler();
        HttpUtil.init(getApplicationContext());

        super.onRestart();
    }

    void close(){

        storeActiveList.clear();
        if(storeActiveList != null)
            storeActiveList = null;

    }

    @Override
    protected void onDestroy() {

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                //开启线程保存文件
                adapter.saveCircleToFile(fileName);
                Log.e("=========>", "保存成功" + fileName);

            }
        });
        thread.start();
        close();

        super.onDestroy();
    }




}
